package personal.vivian.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import personal.vivian.UserInfoService;
import personal.vivian.entity.SysPermission;
import personal.vivian.entity.SysRole;
import personal.vivian.entity.UserInfo;

public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    UserInfoService userInfoService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        UserInfo userInfo=(UserInfo)principalCollection.getPrimaryPrincipal();
        for (SysRole role:userInfo.getRoleList()){
            simpleAuthorizationInfo.addRole(role.getRole());
            for(SysPermission sysPermission:role.getSysPermissions()){
                simpleAuthorizationInfo.addStringPermission(sysPermission.getPermission());
            }
        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        UserInfo userInfo = userInfoService.findByUsername(username);
        if(userInfo==null){
            return null;
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(userInfo.getUserName(),userInfo.getPassword()/*, ByteSource.util.bytes(userInfo.getCredentialsSalt())*/,getName());
        return simpleAuthenticationInfo;
    }
}
